<?php
namespace app\shop\model;
use app\rbac\model\AdminM;
use think\Validate;
use think\Db;
use app\base\model\Base;
class TypeM extends Base
{

       protected function _V($scene,$data)
       {
           $rule = [
               'name' => 'require',
           ];
        $msg = [
        'name.require' => '类型名称不能为空',

        ];
           $validate = new Validate($rule,$msg);
           $validate->scene('add', ['name']);
           $validate->scene('edit', ['name']);
//           $validate->scene('edit', ['role_name','id']);
           $result = $validate->scene($scene)->check($data);
           if($result === false)
           {
               return $validate->getError();
           }
           else
           {
               return true;
           }

       }

    /**
     * 新增数据
     * @return mixed
     */

    public function add($data)
    {
        //验证数据
        $res = $this->_V('add',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $insertData = [];
        //判断用户
        $insertData['admin_id'] = session('admin_id');
        $insertData['name'] = $data['name'];
        $id = Db::table('shop_type')->insertGetId($insertData);
        if(!$id)
        {
            $this->code = -1;
            $this->msg = '新增失败';
            return false;
        }
        return true;
    }

    /**
     * 全部数据
     */
    public function lst($page = 15)
    {
        $data = Db::table('shop_type')->field('id,name')->paginate($page);
        return $data;
    }

    /**
     * 修改数据
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        $res = $this->_V('edit',$data);
        if($res !== true)
        {
            $this->code = -1;
            $this->msg = $res;
            return false;
        }
        $insertData = [];
        $insertData['name'] = $data['name'];

        $id = Db::table('shop_type')->where('id',$data['id'])->update($insertData);
        if(!$id)
        {
            $this->code = -1;
            $this->msg = '修改失败';
            return false;
        }
        return true;
    }

    /**
     * 删除数据
     * @param $id
     */
    public function del($id)
    {
        $res = Db::table('shop_goods')->where('type_id',$id)->field('id')->find();
        if(!empty($res))
        {
            $this->code = -1;
            $this->msg = '类型下有商品,无法删除';
            return false;
        }
        return Db::table('shop_type')->where('id',$id)->delete();
    }
}
